const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
const ASCII_CHARS = /[\x00-\xff]+/g;
/**
 * 将日期转换成指定的格式，如dateFormat(new Date(),"yyyy-MM-dd hh:mm:ss") ==> 2019-07-02 08:09:04
 * @param {日期} val
 * @param {转换后的格式} fmt 
 */
export function dateFormat(val,fmt) { 
    if(isNaN(val) && !isNaN(Date.parse(val))){
       return val
    }
    
    let o = {
        "M+": val.getMonth() + 1, //月份 
        "d+": val.getDate(), //日 
        "h+": val.getHours(), //小时 
        "m+": val.getMinutes(), //分 
        "s+": val.getSeconds(), //秒 
        "q+": Math.floor((val.getMonth() + 3) / 3), //季度 
        "S": val.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o){
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

/**
 * 将字符串转成日期格式 
 * {@param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd}} param 
 */
export function chgStrToDate(param,needHmi){
  let retDate;
  if(param instanceof Date){
    if(needHmi){
      return new Date(param.getFullYear(),param.getMonth(),param.getDate(),param.getHours(),param.getMinutes(),param.getSeconds());
    }else {
      return new Date(param.getFullYear(),param.getMonth(),param.getDate());
    }
  } else {
    let dateStr = param.replace(/-|\//g,'');
    let year = parseInt(dateStr.substr(0,4));
    let month = parseInt(dateStr.length > 4 && dateStr.substr(4,2))-1;
    let day = parseInt(dateStr.length > 6 && dateStr.substr(6,2));
    if(dateStr.length > 8){//还有时分秒
      dateStr = dateStr.replace(/:|\s+/g,'');
      let h = parseInt(dateStr.length > 8 && dateStr.substr(8,2)) || 0;
      let m = parseInt(dateStr.length > 10 && dateStr.substr(10,2)) || 0;
      let s = parseInt(dateStr.length > 12 && dateStr.substr(12,2)) || 0;
      retDate = new Date(year,month,day,h,m,s)
    }else {
      retDate = new Date(year,month,day)
    }
  }
  return retDate;
}
/**
 * 比较两个日期 aparam 比 bparam大返回1  小返回-1 相等返回0
 * @param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd} aparam
 * @param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd}  bparam
 */
export function cmpDateOrStr(aparam,bparam){
  let retCode = 0;
  let adate = chgStrToDate(aparam)
  let bdate = chgStrToDate(bparam);
  if(adate > bdate){
    retCode = 1;
  }else if(adate < bdate){
    retCode = -1;
  }else {
    retCode = 0;
  }

  return retCode;
}
export function getRect(el) {
    if (el instanceof window.SVGElement) {
      let rect = el.getBoundingClientRect()
      return {
        top: rect.top,
        left: rect.left,
        width: rect.width,
        height: rect.height
      }
    } else {
      return {
        top: el.offsetTop,
        left: el.offsetLeft,
        width: el.offsetWidth,
        height: el.offsetHeight
      }
    }
  }
  
  export function imageIsExist(url){
    return new Promise((resolve) => {
      var img = new Image();
      img.onload = function () {
          if (this.complete == true){
              resolve(true);
              img = null;
          }
      }
      img.onerror = function () {
          resolve(false);
          img = null;
      }
      img.src = url;
    });
  }


  export function addClass(el, className) {

    if(!el){
      return;
    }
    el.classList.add(className);
  }
  export function removeClass(el, cls) {
    if (!el || !cls) return;
    var classes = cls.split(' ');
    var curClass = ' ' + el.className + ' ';
  
    for (var i = 0, j = classes.length; i < j; i++) {
      var clsName = classes[i];
      if (!clsName) continue;
  
      if (el.classList) {
        el.classList.remove(clsName);
      } else {
        if (hasClass(el, clsName)) {
          curClass = curClass.replace(' ' + clsName + ' ', ' ');
        }
      }
    }
    if (!el.classList) {
      el.className = trim(curClass);
    }
  };
  export const getStyle = function(element, styleName) {
      if (!element || !styleName) return null;
      styleName = camelCase(styleName);
      if (styleName === 'float') {
        styleName = 'cssFloat';
      }
      try {
        var computed = document.defaultView.getComputedStyle(element, '');
        return element.style[styleName] || computed ? computed[styleName] : null;
      } catch (e) {
        return element.style[styleName];
      }
  }
  
  // \s：空格 \uFEFF：字节次序标记字符 \xA0：禁止自动换行空白符，相当于html中的&nbsp;
  export const trim = function(string) {
    return (string || '').replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
  /* istanbul ignore next */
  const camelCase = function(name) {
    return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
      return offset ? letter.toUpperCase() : letter;
    });
  };
  
  

  export const on = (function() {
    if (document.addEventListener) {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.addEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.attachEvent('on' + event, handler);
        }
      };
    }
  })();
  
  /* istanbul ignore next */
  export const off = (function() {
    if (document.removeEventListener) {
      return function(element, event, handler) {
        if (element && event) {
          element.removeEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event) {
          element.detachEvent('on' + event, handler);
        }
      };
    }
  })();
  
  /* istanbul ignore next */
  export const once = function(el, event, fn) {
    var listener = function() {
      if (fn) {
        fn.apply(this, arguments);
      }
      off(el, event, listener);
    };
    on(el, event, listener);
  };

  export function debounce(func, delay) {
    let timer;
    return function (...args) {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        func.apply(this, args);
      }, delay)
    }
  }

  //从数组_arr中删除_obj对象
export function removeObjWithArr (_arr,_obj) {
	//debugger;
    var length = _arr.length;
    for(var i = 0; i < length; i++)
    {
        if(JSON.stringify(_arr[i]) == JSON.stringify(_obj))
        {
            if(i == 0)
            {
                _arr.shift(); //删除并返回数组的第一个元素
                return;
            }
            else if(i == length-1)
            {
                _arr.pop();  //删除并返回数组的最后一个元素
                return;
            }
            else
            {
                _arr.splice(i,1); //删除下标为i的元素
                return;
            }
        }
    }
};

//从数组_arr中删除_obj对象中属性keyName相同的
export function removeObjWithKey (_arr,_obj,keyName) {
	//debugger;
  var length = _arr.length;
  for(var i = 0; i < length; i++)
  {
      if(_arr[i][keyName] == _obj[keyName])
      {
          if(i == 0)
          {
              _arr.shift(); //删除并返回数组的第一个元素
              return;
          }
          else if(i == length-1)
          {
              _arr.pop();  //删除并返回数组的最后一个元素
              return;
          }
          else
          {
              _arr.splice(i,1); //删除下标为i的元素
              return;
          }
      }
  }
};

/**
 * 
 * @param {*} arr 数组
 * @param {*} key 对象中的属性
 * @param {排序  asc 升序  desc 降序} order 默认升序 
 */
export function cmpArrayByKey(arr,key,order='asc'){
  if(!arr || arr.length < 1){
    return;
  }
  if(!arr[0][key]){
    return;
  }
  let orderNum = 1;
  if(order == 'desc'){
    orderNum = -1;
  }
  function compare(key) {
    return function (a, b) {
      let value1 = a[key];
      let value2 = b[key];
      if(value1 < value2){
        return orderNum * -1;
      }
      if(value1 > value2){
          return orderNum * 1;
      }
      return 0;
    }
  }
  return arr.sort(compare(key));
}

export function getSessionId(){
  let c_name = 'JSESSIONID';
  let retSessionId = 'a1e044eb0903b05d1921776a2824';
  console.info(document.cookie);
  if(document.cookie.length>0){
     let c_start=document.cookie.indexOf(c_name + "=")
     if(c_start!=-1){ 
       c_start=c_start + c_name.length+1 
       let c_end=document.cookie.indexOf(";",c_start)
       if(c_end==-1) c_end = document.cookie.length
       retSessionId = unescape(document.cookie.substring(c_start,c_end));
     }
  }
  return retSessionId;
}

export function getQueryVariable(){
  let query = window.location.search.substring(1);
  if(!query){
      query = window.location.hash;
      let wenIdx = query.indexOf('?');
      query = query.substr(wenIdx + 1);
  }
  console.info(query);
  let vars = query.split("&");
  let qryMap = {};
  for (let i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      let value = pair[1];
      if(pair.length > 2){//针对这样的参数 token=V8x7/bXcqAw====3
          for(let j = 2; j < pair.length; j++){
              if(pair[j]){
                  value += pair[j];
              } else {
                  value += '=';
              }
          }
      }
      qryMap[pair[0]] = value;
  }
  return qryMap;
}

//判断是不是ASCII码
export function isAsciiChar(str){
  return ASCII_CHARS.test(str);
}